#!/usr/bin/env python
# -*- coding:utf-8 -*-

import traceback
import json
from cool_api.client import APIClient
from cool_api.encryptor import AESEncryptor
from app.config.settings import CAS_CONFIG

BASE_URL = CAS_CONFIG.get("base_url")
APPID = CAS_CONFIG.get("appid")
SECRET = CAS_CONFIG.get("secret")

encryptor = AESEncryptor(SECRET)
api_client = APIClient(APPID, SECRET, encryptor, BASE_URL)

HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36'}


def request_cas(data):
    url = data.get("url", "")
    params = data.get("body", {})
    if (not all([url, params])) or (APPID not in url):
        return False, "参数错误"
    try:
        resp = api_client.api_call(
            url,
            encrypted_params=params,
            headers=HEADERS,
            timeout=10
        )
    except Exception:
        traceback.print_exc()
        return False, '通行证错误'
    # return True, resp.decode()
    try:
        data = json.loads(resp.decode())
    except json.JSONDecodeError:
        return False, '通行证返回结果错误'
    if data.get('status') == 'failed':
        return False, data.get('message')
    ret = data.get("ret")
    if ret:
        return True, ret
    return True, data


if __name__ == "__main__":
    d = {
        "url": "/accounts/scanv/get_qrcode_url/",
        "body": {"username": "admin@knownsec.com"}
    }
    print(request_cas(d))

